package pwd.allen.util;

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;

import java.io.InputStream;
import java.rmi.server.ExportException;
import java.util.Properties;

public class ConnectionUtil {
    /**
     * 建立与RabbitMQ的连接
     *
     * 问题
     *  （1）com.rabbitmq.client.ShutdownSignalException: connection error; protocol method: #method<connection.close>(reply-code=530, reply-text=NOT_ALLOWED - access to vhost 'my_vhost' refused for user 'guest', class-id=10, method-id=40)
     *      处理：帐号要有对应virtual host的权限
     *
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {

        Properties properties = new Properties();
        try(InputStream inputStream = ClassLoader.getSystemResourceAsStream("rabbit.properties")) {
            properties.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务地址
        factory.setHost(properties.getProperty("host"));
        //端口
        factory.setPort(Integer.parseInt(properties.getProperty("port")));
        //设置账号信息，用户名、密码、vhost
        factory.setVirtualHost(properties.getProperty("virtual-host"));
        factory.setUsername(properties.getProperty("username"));
        factory.setPassword(properties.getProperty("password"));
        // 通过工程获取连接
        return factory.newConnection();
    }

}
